package commonsService

import (
	"CommonsProject/models/systemModel"
	"CommonsProject/pkg/tools/bcryptTool"
	"CommonsProject/pkg/tools/jwtTool"
	"CommonsProject/pkg/tools/redisTool"
	"CommonsProject/repository/systemRepository"
	"context"
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"time"
)

type CommunalService struct {
	UserRepository *systemRepository.SysUserRepository
}

// LoginUser 用户登录
func (service *CommunalService) LoginUser(ctx context.Context, user *systemModel.SysUser) gin.H {
	var dbUser systemModel.SysUser = systemModel.SysUser{Username: user.Username}
	service.UserRepository.LoginUser(&dbUser)
	if user.Password == nil {
		panic(errors.New("用户名不存在！"))
	}

	//校验密码
	bcryptTool.ComparePwd(*dbUser.Password, *user.Password)
	redisTool.ClientRedis.Set(ctx, fmt.Sprintf("%s:%d", redisTool.LOGIN_USER_REDIS_PREFIX, dbUser.ID), user, time.Hour*24)

	token := jwtTool.GeneratorToken(dbUser.ID)
	return gin.H{
		"token": token,
		"user":  dbUser,
	}
}
